//
//  ModelExtension.swift
//  testRequest
//
//  Created by 鲜恬科技 on 2019/3/27.
//  Copyright © 2019 鲜恬科技. All rights reserved.
//


import Foundation
import RxSwift
import Moya
import ObjectMapper

extension Observable {
    //在这里处理拿到的json数据  map成对像 dict为返回的数据
    func mapObject<T: Mappable>(type: T.Type) -> Observable<T> {
        return self.map { response in
            //if response is a dictionary, then use ObjectMapper to map the dictionary
            //if not throw an error
            guard var dict = response as? [String: Any] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            //return Mapper<T>().map(JSON: dict["data"] as! [String : Any])!
            printLog(response)
            if (dict["code"] == nil) {
                dict["code"] = (dict["status"] ?? 0)
                dict["msg"] = (dict["message"] ?? "") as! String
            }else if (dict["message"] != nil) {
                dict["msg"] = (dict["message"] ?? "") as! String
            }
            return Mapper<T>().map(JSON: dict)!
        }
    }
    
    func mapArray<T: Mappable>(type: T.Type) -> Observable<[T]> {
        return self.map { response in
            //if response is an array of dictionaries, then use ObjectMapper to map the dictionary
            //if not, throw an error
            
            guard let dict = response as? [String: Any] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            
            guard let array = dict["data"] as? [Any] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
            
            guard let dicts = array as? [[String: Any]] else {
                throw RxSwiftMoyaError.ParseJSONError
            }
           
            return Mapper<T>().mapArray(JSONArray: dicts)
        }
    }
}

enum RxSwiftMoyaError: String {
    case ParseJSONError
    case OtherError
}

extension RxSwiftMoyaError: Swift.Error { }


